# -*- coding: utf-8 -*-
# import asyncio
import json
# import logging
import os
import random
import re
import time
import urllib.parse
import uuid

from PyQt5.QtWidgets import QApplication
import requests

from config import global_config
from crypto import aes_cbc_pkcs7
from jd_assistant_app import JD
from timer import Timer
from util import (
    parse_json,
    parse_json_new,
    get_current_time,
    get_hmacsha256,
    get_hmacsha512,
    get_hmacshamd5,
    get_sha256,
    get_sha512,
    get_md5,
    get_date,
    get_sha128,
    xapieidtokenEncrypt,
    generate_random_string,
    getSignStr,
    dict_json,
    get_fp43
)

# from asyncio import get_event_loop
# from pyppeteer import launch

COOKIES_FILE_PATH = 'jd_cookies.txt'
# pyppeteer_level = logging.WARNING
# logging.getLogger('pyppeteer').setLevel(pyppeteer_level)
# logging.getLogger('websockets.protocol').setLevel(pyppeteer_level)
# pyppeteer_logger = logging.getLogger('pyppeteer')
# pyppeteer_logger.setLevel(logging.WARNING)
from PyQt5 import QtTest
from core import sign_uuid, body_enc
# from requests.adapters import HTTPAdapter


class JD_m(object):
    def __init__(self):
        self.sess = requests.session()
        # self.sess.mount('https://api.m.jd.com', DESAdapter())
        # self.sess.mount('http://', HTTPAdapter(max_retries=3))
        # self.sess.mount('https://', HTTPAdapter(max_retries=3))
        self.traceId = self.random_char(19)
        self.eid = ''
        self.aid = ''
        self.phone = ''
        self.uuid = str(uuid.uuid1())
        self.send_message = global_config.getboolean('messenger', 'enable')
        self.user = '',
        self.ui = ''
        self.area = global_config.get('config', 'area')
        self.orderInfo = dict()
        self.pin = ''
        self.app = JD()
        self.x_api_eid_token = ''
        self.ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1'
        self.seckillUserAgent = ''
        self.h5st_algo = {'b63ff': {'fp': '', 'tk': '', 'rd': '', 'enc': ''},
                          'bd265': {'fp': '', 'tk': '', 'rd': '', 'enc': ''},
                          'cc85b': {'fp': '', 'tk': '', 'rd': '', 'enc': ''},
                          '12bda': {'fp': '', 'tk': '', 'rd': '', 'enc': ''},
                          '01a47': {'fp': '', 'tk': '', 'rd': '', 'enc': ''}
                          }  # h5st算法所需加密信息
        self.deviceId = sign_uuid()
        self.currentIp = ''

    def random_char(self, length):
        # 定义一个空列表
        string = []
        for i in range(length):
            x = str(random.randint(0, 9))
            string.append(x)
        string = ''.join(string)
        return string

    def aes_encrypt(self, body, key):
        return aes_cbc_pkcs7.encrypt(text=body, key=key)

    def parse_area(self, areaid):
        parse_area = areaid.replace('_', '-')
        return parse_area

    # def screen_size(self):
    #     # 使用tkinter获取屏幕大小
    #     import tkinter
    #     tk = tkinter.Tk()
    #     width = tk.winfo_screenwidth()
    #     height = tk.winfo_screenheight()
    #     tk.quit()
    #     return width, height

    # async def get_user_ck(self, sku):
    #     # 建立一个浏览器对象
    #     launch_args = {
    #         'headless': False,
    #         'dumpio': True,
    #         "devtools": True,
    #         'deviceName': 'Galaxy S5',
    #         'userDataDir': r'./userdata',
    #         "args": [
    #             '--disable-infobars',  # 关闭自动化提示框
    #             '--no-sandbox',  # 关闭沙盒模式
    #             '--start-maximized',  # 窗口最大化模式
    #             '--user-agent=Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1'
    #         ],
    #     }
    #     browser = await launch(**launch_args)
    #     # 打开新的标签页
    #     page = await browser.newPage()
    #     await page.setUserAgent(
    #         'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1')
    #     await page.evaluateOnNewDocument(
    #         '() =>{ Object.defineProperties(navigator,''{ webdriver:{ get: () => false } });window.navigator.chrome = { runtime: {},  };Object.defineProperties(navigator,\'languages\'{ get: () => [\'en-US\', \'en\'] });Object.defineProperty(navigator, \'plugins\', { get: () => [1, 2, 3, 4, 5,6], })}')
    #     # 设置网页视图大小
    #     width, height = self.screen_size()
    #     await page.setViewport(viewport={'width': width, 'height': height, 'isMobile': True})
    #     # 访问目标url网页
    #     await page.goto(
    #         'https://plogin.m.jd.com/login/login?appid=300&returnurl=https%3A%2F%2Fwq.jd.com%2Fpassport%2FLoginRedirect%3Fstate%3D2445093180%26returnurl%3Dhttps%253A%252F%252Fhome.m.jd.com%252FmyJd%252Fhome.action&source=wq_passport')
    #     target1 = page.evaluate('''()=>{document.querySelector('.J_ping')}''')
    #     await self.wait_navigation(page, target1)
    #     target2 = page.evaluate('''()=>{document.querySelector('.page-notice')}''')
    #     if target2:
    #         await self.wait_navigation(page, target2)
    #         target3 = page.evaluate('''()=>{document.querySelector('#mCommonHome')}''')
    #         if target3:
    #             await self.wait_navigation(page, target3)
    #         self.ui.console.append("{0}   登录完成".format(get_current_time()))
    #         await asyncio.sleep(2)
    #         cookies_list = await page.cookies()
    #         cookies = {}
    #         for cookie in cookies_list:
    #             cookies[cookie.get('name')] = cookie.get('value')
    #         # 保存cookies
    #         self._serialization_cookies(ck=cookies)
    #         self.sess.cookies = self.deserialization_cookies()
    #         await browser.close()
    #         self.get_login_user()
    #         self.queryScore()
    #         self.get_adressid()
    #         self.ui.console.append("{0}   开启预约".format(get_current_time()))
    #         self.yuyue(skuid=sku)
    #         # self.batch_cancel_favorite()
    #         # self.favCommAdd(sku=sku)
    #     else:
    #         # await page.waitForNavigation({'timeout': 1200000})
    #         while not await page.querySelector('#mCommonHome'):
    #             await asyncio.sleep(0.2)
    #             pass
    #         self.ui.console.append("{0}   登录完成".format(get_current_time()))
    #
    #         await asyncio.sleep(1)
    #         cookies_list = await page.cookies()
    #         cookies = {}
    #         for cookie in cookies_list:
    #             cookies[cookie.get('name')] = cookie.get('value')
    #         # 保存cookies
    #         self._serialization_cookies(ck=cookies)
    #         self.sess.cookies = self.deserialization_cookies()
    #         await browser.close()
    #         self.get_login_user()
    #         self.queryScore()
    #         self.get_adressid()
    #         self.ui.console.append("{0}   开启预约".format(get_current_time()))
    #         self.yuyue(skuid=sku)
    #         self.batch_cancel_favorite()
    #         self.favCommAdd(sku=sku)

    # async def wait_navigation(self, page, events):
    #     await asyncio.wait([
    #         events,
    #         page.waitForNavigation({'timeout': 1200000}),
    #     ])

    def _serialization_cookies(self, ck):
        with open(COOKIES_FILE_PATH, 'w+', encoding='utf-8') as file:
            json.dump(ck, file)
            self.ui.console.append("{0}   保存cookies文件成功！".format(get_current_time()))

    def load_cookies(self, ui):
        # 2023-03-04-新增appck转mck
        self.app.initEp()
        if self.app.loadCookie(ui):
            self.sess.cookies = self.app.deserialization_cookies()
            self.appCk_to_mCk()
            return True
        else:
            if not os.path.exists(COOKIES_FILE_PATH):
                return False
            # 2、加载cookies
            self.sess.cookies = self.deserialization_cookies()
            # 3、判断cookies是否过期
            try:
                if self.validate_cookies():
                    return True
                else:
                    os.remove(COOKIES_FILE_PATH)
                    self.ui.console.append("{0}   cookies过期，删除cookies文件！".format(get_current_time()))
                    return False
            except Exception as e:
                os.remove(COOKIES_FILE_PATH)
                self.ui.console.append("{0}   cookies过期，删除cookies文件！".format(get_current_time()))
                return False

    def deserialization_cookies(self):
        with open(COOKIES_FILE_PATH, 'r+', encoding='utf-8') as file:
            cookie_dict = json.load(file)
            cookies = requests.utils.cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True)
            return cookies

    def get_seckill_userAgent(self):
        # 生成秒杀请求头
        ep = {
            'hdid': 'JM9F1ywUPwflvMIpYPok0tt5k9kW4ArJEU3lfLhxBqw=',
            'ts': round(time.time() * 1000),
            'ridx': -1,
            'cipher': {
                'sv': 'CJO=',
                'ad': body_enc(self.deviceId),
                'od': body_enc(self.deviceId),
                'ov': 'CzK=',
                'ud': body_enc(self.deviceId)
            },
            'ciphertype': 5,
            'version': '1.2.0',
            'appname': 'com.jd.jdlite'
        }
        self.seckillUserAgent = 'appBuild/22790;ef/1;ep/' + urllib.parse.quote(json.dumps(
            ep)) + 'jdSupportDarkMode/0;Mozilla/5.0 (Linux; Android 11; SM-G9980 Build/RP1A.200720.012; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/110.0.5481.153 Mobile Safari/537.36'

    def appCk_to_mCk(self):
        jump = self.app.getToken(url='https://plus.m.jd.com/user/home')
        un_params = {
            'tokenKey': jump[0],
            'to': 'https://plus.m.jd.com/user/home'
        }
        un_headers = {
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
            'User-Agent': self.seckillUserAgent,
            'X-Requested-With': 'com.jingdong.app.mall',
            'Host': 'un.m.jd.com'
        }
        self.sess.get(url=jump[1], headers=un_headers, params=un_params, allow_redirects=False)

    def login(self, sku, ui):
        self.ui = ui
        self.proxy()
        self.get_seckill_userAgent()
        self.get_x_api_eid_token()
        if self.load_cookies(ui):
            self.get_login_user()
            self.get_adressid()
            self.ui.console.append("{0}   开启预约".format(get_current_time()))
            self.yuyue(skuid=sku)
            return True
        else:
            self.ui.console.append("{0}   本次登录失效，请退出程序并检查对应缓存文件".format(get_current_time()))
            return False
            # self.ui.console.append("{0}   正在拉起浏览器获取cookies中....".format(get_current_time()))
            # QApplication.processEvents()
            # get_event_loop().run_until_complete(self.get_user_ck(sku=sku))

    def get_current_ip_address(self):
        response = self.sess.get("https://www.ipplus360.com/getIP")
        data = response.json()
        if isinstance(data, dict):
            ip = data['data']
        else:
            ip = data
        self.ui.console.append("{0}   当前IP地址:{1}".format(get_current_time(), ip))

    def proxy(self):
        proxy_url = self.ui.proxy_api_address.toPlainText().replace(" ", "")
        white_list_api = self.ui.proxy_white_list.toPlainText().replace(" ", "")
        if proxy_url != '':
            self.ui.console.append("{0}   检测到当前启用代理".format(get_current_time()))
            if white_list_api != '':
                self.set_current_ip_whitelist()
            self.set_proxy_address()

    # 设置代理地址
    def set_proxy_address(self):
        proxy_url = self.ui.proxy_api_address.toPlainText().replace(" ", "")
        self.sess.proxies = {}
        self.app.sess.proxies = {}
        headers = {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1'
        }
        proxies = {
            'https': ''
        }
        resp = self.sess.get(url=proxy_url, headers=headers)
        resp_json = json.loads(resp.text)
        if resp_json['code'] == 'SUCCESS':
            target = random.choice(resp_json['data'])
            proxies['https'] = 'http://{0}/'.format(target['server'])
            self.sess.proxies = proxies
            self.app.sess.proxies = proxies
            self.ui.console.append("{0}   成功更换代理ip地址".format(get_current_time()))
            self.get_current_ip_address()
        else:
            self.ui.console.append("{0}   {1}".format(get_current_time(), resp_json['msg']))

    # 将当前ip地址加入芝麻代理白名单
    def set_current_ip_whitelist(self):
        # response = self.sess.get("https://www.ipplus360.com/getIP")
        # data = response.json()
        # ip = data['data']
        url = self.ui.proxy_white_list.toPlainText().replace(" ", "")
        url = url + self.currentIp
        headers = {
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1'
        }
        resp = self.sess.get(url=url, headers=headers)
        if resp.json()['Code'] != 0:
            self.ui.console.append("{0}   {1}".format(get_current_time(), '设置代理白名单失败：' + resp.json()['Msg']))
        else:
            self.ui.console.append("{0}   {1}".format(get_current_time(), '设置代理白名单成功'))

    def get_x_api_eid_token(self):
        """
               获取x-api-eid-token
               :return:
               """
        url = 'https://gia.jd.com/jsTk.do'
        headers = {
            'Accept': '*/*',
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
            'Host': 'gia.jd.com',
            'User-Agent': self.seckillUserAgent,
            'X-Requested-With': 'com.jingdong.app.mall',
        }
        a = {
            "pin": "",
            "oid": "",
            "bizId": "jx_h5_common",
            "fc": "",
            "mode": "strict",
            "p": "s",
            "fp": self.get_fp(),
            "ctype": 1,
            "v": "3.2.1.0",
            "f": "3",
            "o": "wqs.jd.com/sns/202210/20/makemoneyshop/index.html",
            "qs": "",
            "jsTk": "",
            "qi": "",
        }
        d = {
            "ts": {
                "deviceTime": round(time.time() * 1000),
                "deviceEndTime": round(time.time() * 1000)
            },
            "ca": {
                "tdHash": str(uuid.uuid4()).replace('-', ''),
                "contextName": "webgl,experimental-webgl",
                "webglversion": "WebGL 1.0 (OpenGL ES 2.0 Chromium)",
                "shadingLV": "WebGL GLSL ES 1.0 (OpenGL ES GLSL ES 1.0 Chromium)",
                "vendor": "WebKit",
                "renderer": "WebKit WebGL",
                "extensions": [
                    "ANGLE_instanced_arrays",
                    "EXT_blend_minmax",
                    "EXT_color_buffer_half_float",
                    "EXT_float_blend",
                    "EXT_texture_filter_anisotropic",
                    "WEBKIT_EXT_texture_filter_anisotropic",
                    "EXT_sRGB",
                    "OES_element_index_uint",
                    "OES_fbo_render_mipmap",
                    "OES_standard_derivatives",
                    "OES_texture_float",
                    "OES_texture_float_linear",
                    "OES_texture_half_float",
                    "OES_texture_half_float_linear",
                    "OES_vertex_array_object",
                    "WEBGL_color_buffer_float",
                    "WEBGL_compressed_texture_astc",
                    "WEBGL_compressed_texture_etc",
                    "WEBGL_compressed_texture_etc1",
                    "WEBGL_debug_renderer_info",
                    "WEBGL_debug_shaders",
                    "WEBGL_depth_texture",
                    "WEBKIT_WEBGL_depth_texture",
                    "WEBGL_lose_context",
                    "WEBKIT_WEBGL_lose_context",
                    "WEBGL_multi_draw"
                ],
                "wuv": "Qualcomm",
                "wur": "Adreno (TM) 730"
            },
            "m": {
                "compatMode": "CSS1Compat"
            },
            "fo": ["Bauhaus 93", "Casual"],
            "n": {
                "vendorSub": "",
                "productSub": "20030107",
                "vendor": "Google Inc.",
                "maxTouchPoints": 5,
                "hardwareConcurrency": 8,
                "cookieEnabled": True,
                "appCodeName": "Mozilla",
                "appName": "Netscape",
                "appVersion": "",
                "platform": "Linux aarch64",
                "product": "Gecko",
                "userAgent": "",
                "language": "zh-CN",
                "onLine": True,
                "webdriver": False,
                "javaEnabled": False,
                "deviceMemory": 8,
                "enumerationOrder": [
                    "vendorSub",
                    "productSub",
                    "vendor",
                    "maxTouchPoints",
                    "userActivation",
                    "doNotTrack",
                    "geolocation",
                    "connection",
                    "plugins",
                    "mimeTypes",
                    "webkitTemporaryStorage",
                    "webkitPersistentStorage",
                    "hardwareConcurrency",
                    "cookieEnabled",
                    "appCodeName",
                    "appName",
                    "appVersion",
                    "platform",
                    "product",
                    "userAgent",
                    "language",
                    "languages",
                    "onLine",
                    "webdriver",
                    "getBattery",
                    "getGamepads",
                    "javaEnabled",
                    "sendBeacon",
                    "vibrate",
                    "scheduling",
                    "mediaCapabilities",
                    "locks",
                    "wakeLock",
                    "usb",
                    "clipboard",
                    "credentials",
                    "keyboard",
                    "mediaDevices",
                    "storage",
                    "serviceWorker",
                    "deviceMemory",
                    "bluetooth",
                    "getUserMedia",
                    "requestMIDIAccess",
                    "requestMediaKeySystemAccess",
                    "webkitGetUserMedia",
                    "clearAppBadge",
                    "setAppBadge"
                ]
            },
            "p": [],
            "w": {
                "devicePixelRatio": 2.7500000596046448,
                "screenTop": 0,
                "screenLeft": 0
            },
            "s": {
                "availHeight": 851,
                "availWidth": 393,
                "colorDepth": 24,
                "height": 851,
                "width": 393,
                "pixelDepth": 24
            },
            "sc": {
                "ActiveBorder": "rgb(255, 255, 255)",
                "ActiveCaption": "rgb(204, 204, 204)",
                "AppWorkspace": "rgb(255, 255, 255)",
                "Background": "rgb(99, 99, 206)",
                "ButtonFace": "rgb(221, 221, 221)",
                "ButtonHighlight": "rgb(221, 221, 221)",
                "ButtonShadow": "rgb(136, 136, 136)",
                "ButtonText": "rgb(0, 0, 0)",
                "CaptionText": "rgb(0, 0, 0)",
                "GrayText": "rgb(128, 128, 128)",
                "Highlight": "rgb(181, 213, 255)",
                "HighlightText": "rgb(0, 0, 0)",
                "InactiveBorder": "rgb(255, 255, 255)",
                "InactiveCaption": "rgb(255, 255, 255)",
                "InactiveCaptionText": "rgb(127, 127, 127)",
                "InfoBackground": "rgb(251, 252, 197)",
                "InfoText": "rgb(0, 0, 0)",
                "Menu": "rgb(247, 247, 247)",
                "MenuText": "rgb(0, 0, 0)",
                "Scrollbar": "rgb(255, 255, 255)",
                "ThreeDDarkShadow": "rgb(102, 102, 102)",
                "ThreeDFace": "rgb(192, 192, 192)",
                "ThreeDHighlight": "rgb(221, 221, 221)",
                "ThreeDLightShadow": "rgb(192, 192, 192)",
                "ThreeDShadow": "rgb(136, 136, 136)",
                "Window": "rgb(255, 255, 255)",
                "WindowFrame": "rgb(204, 204, 204)",
                "WindowText": "rgb(0, 0, 0)"
            },
            "ss": {
                "cookie": True,
                "localStorage": True,
                "sessionStorage": True,
                "globalStorage": False,
                "indexedDB": True
            },
            "tz": -480,
            "lil": "",
            "wil": ""
        }
        params = {
            'a': xapieidtokenEncrypt(a)
        }
        data = {
            'd': xapieidtokenEncrypt(d)
        }
        resp = self.sess.post(url, headers=headers, params=params, data=data)
        resp_json = json.loads(resp.text)
        try:
            self.x_api_eid_token = resp_json['data']['token']
            self.eid = resp_json['data']['eid']
            # self.sess.cookies.set('3AB9D23F7A4B3C9B', resp_json['data']['eid'])
            # self.sess.cookies.set('3AB9D23F7A4B3CSS', self.x_api_eid_token)
        except:
            self.ui.console.append("{0}   获取x-api-eid-token失败!".format(get_current_time()))

    def get_fp(self):
        """
                       获取浏览器指纹,根据参数去sha128加密。京东自定义了sha128加密算法。发现随机生成的也能用
                       :return:
                       """
        arr = [
            self.ua,
            "zh-CN",
            "applewebkit_chrome",
            "537.36",
            "linux",
            "NA",
            random.randint(1, 99),
            "851x393",
            random.randint(1, 1000),
            "sessionStorageKey",
            "localStorageKey",
            "indexedDbKey",
            "openDatabase",
            "NA",
            "Win32",
            random.randint(1, 99),
            "NA",
            "",
            "",
            "§extensions:ANGLE_instanced_arrays;EXT_blend_minmax;EXT_color_buffer_half_float;EXT_disjoint_timer_query;EXT_float_blend;EXT_frag_depth;EXT_shader_texture_lod;EXT_texture_compression_bptc;EXT_texture_compression_rgtc;EXT_texture_filter_anisotropic;EXT_sRGB;KHR_parallel_shader_compile;OES_element_index_uint;OES_fbo_render_mipmap;OES_standard_derivatives;OES_texture_float;OES_texture_float_linear;OES_texture_half_float;OES_texture_half_float_linear;OES_vertex_array_object;WEBGL_color_buffer_float;WEBGL_compressed_texture_s3tc;WEBGL_compressed_texture_s3tc_srgb;WEBGL_debug_renderer_info;WEBGL_debug_shaders;WEBGL_depth_texture;WEBGL_draw_buffers;WEBGL_lose_context;WEBGL_multi_draw§extensions:ANGLE_instanced_arrays;EXT_blend_minmax;EXT_color_buffer_half_float;EXT_disjoint_timer_query;EXT_float_blend;EXT_frag_depth;EXT_shader_texture_lod;EXT_texture_compression_bptc;EXT_texture_compression_rgtc;EXT_texture_filter_anisotropic;EXT_sRGB;KHR_parallel_shader_compile;OES_element_index_uint;OES_fbo_render_mipmap;OES_standard_derivatives;OES_texture_float;OES_texture_float_linear;OES_texture_half_float;OES_texture_half_float_linear;OES_vertex_array_object;WEBGL_color_buffer_float;WEBGL_compressed_texture_s3tc;WEBGL_compressed_texture_s3tc_srgb;WEBGL_debug_renderer_info;WEBGL_debug_shaders;WEBGL_depth_texture;WEBGL_draw_buffers;WEBGL_lose_context;WEBGL_multi_draw§w1[1, 1]§w2[1, 1024]§w38§w4yes§w58§w624§w78§w816§w932§w1016384§w111024§w1216384§w1316§w1416384§w1530§w1616§w1716§w184096§w19[32767, 32767]§w208§w21WebKit WebGL§w22WebGL GLSL ES 1.0 (OpenGL ES GLSL ES 1.0 Chromium)§w230§w24WebKit§w25WebGL 1.0 (OpenGL ES 2.0 Chromium)§wuv:Google Inc. (Intel)§wur:ANGLE (Intel, Intel(R) Iris(R) Xe Graphics Direct3D11 vs_5_0 ps_5_0, D3D11)"
        ]
        encryptStr = "~~~".join(str(x) for x in arr)
        return get_sha128(encryptStr)

    def queryScore(self):
        date = get_date()[0]
        ts = get_date()[1]
        """
        查询用户plus分值
        :return:
        """
        self.h5st_algo['b63ff']['fp'] = get_fp43()
        expandParams = {
            'wc': 1,
            'wd': 0,
            'l': 'zh-CN',
            'ls': 'zh-CN,zh',
            'ml': 0,
            'pl': 0,
            'av': self.seckillUserAgent[self.seckillUserAgent.find("appBuild/") + len("appBuild/"):],
            'ua': self.seckillUserAgent,
            'sua': 'Linux; Android 11; SM-G9980 Build/RP1A.200720.012; wv',
            'pp': {'p1': self.pin, 'p2': self.pin},
            'extend': {
                'wd': 0,
                'l': 0,
                'ls': 0,
                'wk': 0,
                'bu1': '0.1.10',
                'bu2': 0,
                'bu3': 37,
                'bu4': 0
            },
            'pp1': '',
            'w': 390,
            'h': 844,
            'ow': 390,
            'oh': 844,
            'url': 'https://plus.m.jd.com/user/home',
            'og': 'https://plus.m.jd.com',
            'pr': 3.75,
            're': 'https://plus.m.jd.com/index',
            'random': generate_random_string(10),
            'referer': 'https://plus.m.jd.com/index',
            'v': 'h5_file_v4.3.3',
            'ai': 'b63ff',
            'fp': self.h5st_algo['b63ff']['fp']
        }
        algoHeaders = {
            'Host': 'cactus.jd.com',
            'Origin': 'https://plus.m.jd.com',
            'Referer': 'https://plus.m.jd.com/user/home',
            'User-Agent': self.seckillUserAgent,
            'Content-Type': 'application/json',
            'x-rp-client': 'h5_1.0.0',
            'X-Requested-With': 'com.jingdong.app.mall',
        }
        algoPayload = {
            'version': '4.3',
            'fp': self.h5st_algo['b63ff']['fp'],
            'appId': 'b63ff',
            'timestamp': str(round(time.time() * 1000)),
            'platform': 'web',
            'expandParams': self.aes_encrypt(body=json.dumps(expandParams), key='wm0!@w-s#ll1flo('),
            'fv': 'h5_file_v4.3.3',
        }
        self.get_h5st_token(ai='b63ff', headers=algoHeaders, payload=algoPayload)
        enctry_str = self.h5st_algo['b63ff']['tk'] + self.h5st_algo['b63ff']['fp'] + date + '22' + 'b63ff' + \
                     self.h5st_algo['b63ff']['rd']
        key = self.get_h5st_signStr_key(ai='b63ff', enctry_str=enctry_str)
        signStr = 'appid:plus_business&body:' + get_sha256(
            data='{}') + '&functionId:windControl_queryScore_v1'
        url = 'https://api.m.jd.com/api?functionId=windControl_queryScore_v1'
        payload = {
            'appid': 'plus_business',
            'functionId': 'windControl_queryScore_v1',
            'loginType': '2',
            'loginWQBiz': '',
            'scval': '',
            'body': '{}',
            'h5st': self.get_h5st_v43(signStr=signStr, ai='b63ff', date=date, ts=ts, key=key),
            'x-api-eid-token': self.x_api_eid_token
        }
        header = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Referer': 'https://plus.m.jd.com/user/home',
            'User-Agent': self.seckillUserAgent,
            'X-Referer-Page': 'https://plus.m.jd.com/user/home',
            'Origin': 'https://plus.m.jd.com',
            'X-Requested-With': 'com.jingdong.app.mall',
            'x-rp-client': 'h5_1.0.0',
            'Host': 'api.m.jd.com'
        }
        resp = self.sess.post(url=url, headers=header, data=payload)
        resp_json = json.loads(resp.text)
        if resp_json.get('rs'):
            if resp_json['rs']['userSynthesizeScore']['exAddScoreTypeList'][1]['status'] == 0:
                self.ui.score.setText(str(resp_json['rs']['userSynthesizeScore']['totalScore']) + '(未人脸校验)')
            else:
                self.ui.score.setText(str(resp_json['rs']['userSynthesizeScore']['totalScore']))
            return True
        else:
            self.ui.console.append("{0}   获取plus分值失败!".format(get_current_time()))
            return False

    def yuyue(self, skuid):
        t = round(time.time() * 1000)
        url = 'https://api.m.jd.com/api'
        headers = {
            'Origin': 'https://wqs.jd.com',
            'Referer': 'https://wqs.jd.com/',
            'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 16_6 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.6 Mobile/15E148 Safari/604.1',
            'x-rp-client': 'h5_1.0.0',
            'X-Requested-With': 'com.jingdong.app.mall',
            'X-Referer-Page': 'https://wqs.jd.com/item/yuyue_item.shtml'
        }
        body = {
            'dataType': 1,
            'skuId': skuid,
            'sceneval': 2,
            'buid': 325,
            'appCode': 'ms0ca95114',
            'time': t
        }
        sign = getSignStr(data=body)
        body['signStr'] = sign
        body = dict_json(body)
        params = {
            'functionId': 'jxdetail_ass_yuyue_subscribe',
            'appid': 'jx_h5',
            't': t,
            'channel': 'jxh5',
            'cv': '2.2.7',
            'clientVersion': '2.2.7',
            'client': 'jxh5',
            'uuid': self.uuid,
            'cthr': 1,
            'loginType': 2,
            'body': body
        }
        resp = self.sess.get(url=url, headers=headers, params=params, allow_redirects=False)
        resp_json = parse_json(resp.text)
        try:
            if resp_json['retCode'] == '0':
                self.ui.console.append("{0}   {1}".format(get_current_time(), resp_json['list'][0]['replyMsg']))
            else:
                self.ui.console.append("{0}   {1}".format(get_current_time(), resp_json['retMsg']))
        except Exception:
            self.ui.console.append("{0}   预约接口异常".format(get_current_time()))

    def favCommAdd(self, sku):
        """"
        商品添加收藏
        """
        url = 'https://wq.jd.com/fav/comm/FavCommAdd'
        headers = {
            'Referer': 'https://item.m.jd.com/product/{0}.html?u_source=mfootprint'.format(sku),
            'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
            'Host': 'wq.jd.com'
        }
        params = {
            'commId': sku,
            'sceneval': '2',
            't': time.time(),
            'callback': 'addFavA'
        }
        self.sess.get(url=url, headers=headers, params=params)

    def favorite_list(self):
        """"
        获取商品收藏列表
        """
        url = 'https://wq.jd.com/fav/comm/FavCommQueryFilter'
        headers = {
            'Referer': 'https://wqs.jd.com/my/fav/goods_fav.shtml?sceneval=2&ptag=7155.1.8',
            'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
            'Host': 'wq.jd.com'
        }
        params = {
            'cp': '1',
            'pageSize': '10',
            'category': '0',
            'promote': '0',
            'cutPrice': '0',
            'coupon': '',
            'stock': '0',
            'areaNo': self.area,
            '_': time.time(),
            'sceneval': '2',
            'g_login_type': '1',
            'callback': 'jsonpCBKB',
            'g_ty': 'ls'

        }
        resp = self.sess.get(url=url, headers=headers, params=params)
        resp_json = parse_json_new(resp.text)
        return resp_json['data']

    def batch_cancel_favorite(self):
        favoriteList = self.favorite_list()
        if len(favoriteList) > 0:
            commIds = list()
            for i in favoriteList:
                commIds.append(i['commId'])
            commId = ','.join(commIds)
            url = 'https://wq.jd.com/fav/comm/FavCommBatchDel'
            headers = {
                'Referer': 'https://wqs.jd.com/my/fav/goods_fav.shtml?sceneval=2&ptag=7155.1.8',
                'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
                'Host': 'wq.jd.com'
            }
            params = {
                'commId': commId,
                '_': time.time(),
                'sceneval': '2',
                'g_login_type': '1',
                'callback': 'jsonpCBKQ',
                'g_ty': 'ls'

            }
            self.sess.get(url=url, headers=headers, params=params)

    def get_stock(self, sku):
        """
        通过收藏夹查询商品库存
        """
        favoriteList = self.favorite_list()
        if len(favoriteList) > 0:
            for i in favoriteList:
                if i['commId'] == sku:
                    if i['hasStock'] == 1:
                        return True
                    else:
                        return False

    def get_login_user(self):
        self.sess.cookies.set('3AB9D23F7A4B3C9B', self.eid)
        self.sess.cookies.set('3AB9D23F7A4B3CSS', self.x_api_eid_token)
        url = 'https://api.m.jd.com/api'
        headers = {
            'Origin': 'https://my.m.jd.com',
            'Referer': 'https://my.m.jd.com/',
            'x-rp-client': 'h5_1.0.0',
            'X-Requested-With': 'com.jingdong.app.mall',
            'user-agent': self.seckillUserAgent
        }
        data = {
            '_': str(round(time.time() * 1000)),
            'functionId': 'getUserAllPinInfo',
            'appid': 'jd-cphdeveloper-m',
            'loginType': '2',
            'sceneval': '2',
            'g_login_type': '1',
            'g_ty': 'ajax',
            'appCode': 'msc588d6d5',
            'body': '{"tenantCode":"jgm","bizModelCode":"6","bizModeClientType":"M","externalLoginType":"1","url":"https://my.m.jd.com/account/index.html?sceneval=2&appCode=msc588d6d5&source=common","sid":"","USER_FLAG_CHECK":""}'
        }
        resp = self.sess.get(url=url, headers=headers, params=data)
        if resp.status_code == 200:
            resp_json = json.loads(resp.text)
            user = resp_json['userdata']['renderJdData'][0]['msg']['pin']
            # self.uuid = requests.utils.dict_from_cookiejar(self.sess.cookies)['mba_muid']
            # self.eid = requests.utils.dict_from_cookiejar(self.sess.cookies)['3AB9D23F7A4B3C9B']
            self.user = user
            self.pin = urllib.parse.unquote(self.sess.cookies['pt_pin'])
            self.ui.userName.setText(self.pin)
            return True
        else:
            self.ui.console.append("{0}   缓存失效或接口已经下线。请联系huangshiqi".format(get_current_time()))
            return False

    def validate_cookies(self):
        if self.get_login_user():
            return True
        else:
            return False

    def get_adressid(self):
        self.h5st_algo['01a47']['fp'] = get_fp43()
        expandParams = {
            'wc': 0,
            'wd': 0,
            'l': 'zh-CN',
            'ls': 'zh-CN,zh',
            'ml': 0,
            'pl': 0,
            'av': self.seckillUserAgent[self.seckillUserAgent.find("appBuild/") + len("appBuild/"):],
            'ua': self.seckillUserAgent,
            'sua': 'Linux; Android 11; SM-G9980 Build/RP1A.200720.012; wv',
            'pp': {'p1': self.pin, 'p2': self.pin},
            'extend': {
                'wd': 0,
                'l': 0,
                'ls': 0,
                'wk': 0,
                'bu1': '0.1.10',
                'bu2': 0,
                'bu3': 37,
                'bu4': 0
            },
            'pp1': '',
            'w': 390,
            'h': 844,
            'ow': 390,
            'oh': 844,
            'url': 'https://trade.m.jd.com/pay/#/address?sceneval=2&sid=&source=4',
            'og': 'https://trade.m.jd.com',
            'pr': 3.75,
            're': '',
            'random': generate_random_string(10),
            'referer': '',
            'v': 'h5_file_v4.3.3',
            'ai': '01a47',
            'fp': self.h5st_algo['01a47']['fp']
        }
        algoHeaders = {
            'Host': 'cactus.jd.com',
            'Origin': 'https://trade.m.jd.com',
            'Referer': 'https://trade.m.jd.com',
            'User-Agent': self.seckillUserAgent,
            'Content-Type': 'application/json',
            'x-rp-client': 'h5_1.0.0',
            'X-Requested-With': 'com.jingdong.app.mall',
        }
        algoPayload = {
            'version': '4.3',
            'fp': self.h5st_algo['01a47']['fp'],
            'fv': 'h5_file_v4.3.3',
            'appId': '01a47',
            'timestamp': str(round(time.time() * 1000)),
            'platform': 'web',
            'expandParams': self.aes_encrypt(body=json.dumps(expandParams), key='wm0!@w-s#ll1flo('),
        }
        self.get_h5st_token(ai='01a47', headers=algoHeaders, payload=algoPayload)

        date = get_date()[0]
        ts = get_date()[1]
        url = 'https://api.m.jd.com/client.action'
        header = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Origin': 'https://trade.m.jd.com',
            'x-rp-client': 'h5_1.0.0',
            'Referer': 'https://trade.m.jd.com/',
            'X-Requested-With': 'com.jingdong.app.mall',
            'User-Agent': self.seckillUserAgent
        }
        body = '{"deviceUUID":"unknown","appId":"wxae3e8056daea8727","tenantCode":"jgm","bizModelCode":"3","bizModeClientType":"M","token":"3852b12f8c4d869b7ed3e2b3c68c9436","externalLoginType":1,"serialNumber":"ZcTmpGDKS08Bt0fgTvHRij0whhOdr1GA+04n3kZC+Z0sakfQ/cZ6zcU1tczvzWifttvOIYiPIMgXostvMFk2u259zYzw5Pm9wPLUM+rqAdZ6reH8cC8QGLzFoJsJMNvbhpnlxQuiPplSDmos8i9TQwUlyoG89iXaxbiTgk0zUtY=","keyId":"2","jdCombineSign":false}'
        enctry_str = self.h5st_algo['01a47']['tk'] + self.h5st_algo['01a47']['fp'] + date + '22' + '01a47' + \
                     self.h5st_algo['01a47']['rd']
        t = str(round(time.time() * 1000))
        key = self.get_h5st_signStr_key(ai='01a47', enctry_str=enctry_str)
        signStr = 'appid:m_core&body:' + get_sha256(
            body) + '&client:Linux aarch64&clientVersion:2.2.7&functionId:address_queryAddress_m&t:' + t

        params = {
            'client': 'Linux aarch64',
            'clientVersion': '2.2.7',
            'osVersion': 'other',
            'screen': '390*844',
            'networkType': 'false',
            'd_brand': '',
            'd_model': '',
            'lang': 'zh-CN',
            'sdkVersion': '2.2.7',
            'appid': 'm_core',
            'openudid': '',
            'functionId': 'address_queryAddress_m',
            'uuid': '',
            'loginType': '2',
            't': t,
            'body': body,
            'h5st': self.get_h5st_v43(signStr=signStr, ai='01a47', date=date, ts=ts, key=key),
            'x-api-eid-token': self.x_api_eid_token
        }
        resp = self.sess.post(url=url, headers=header, data=params)
        resp_json = json.loads(resp.text)
        # 是否存在默认地址
        hasDefaultAddress = False
        addressTarget = dict()
        try:
            address = resp_json['body']['addressInfoList']
            if len(address) != 0:
                for i in address:
                    if i['defaultAddress']:
                        hasDefaultAddress = True
                        addressTarget = i
                if hasDefaultAddress:
                    # 存在默认地址
                    self.aid = addressTarget['addressId']
                else:
                    # 存在地址，但是没默认地址，取第一条
                    self.aid = address[0]['addressId']
                    # addressDeatil = des_cbc_decrypt(i['fullAddress'], '79475350', '00000000')
                    # self.ui.address.setText(addressDeatil)
            else:
                self.ui.console.append("{0}   账户暂未设置收货地址。程序终止".format(get_current_time()))
                return

        except:
            self.ui.console.append("{0}   获取账户地址异常".format(get_current_time()))

    def get_h5st_signStr_key(self, ai, enctry_str):
        encrypt = self.h5st_algo[ai]['enc']
        tk = self.h5st_algo[ai]['tk']
        key = ''
        if encrypt == 'HmacSHA256':
            key = get_hmacsha256(tk, enctry_str)
        if encrypt == 'HmacSHA512':
            key = get_hmacsha512(tk, enctry_str)
        if encrypt == 'HmacMD5':
            key = get_hmacshamd5(tk, enctry_str)
        if encrypt == 'SHA256':
            key = get_sha256(enctry_str)
        if encrypt == 'SHA512':
            key = get_sha512(enctry_str)
        if encrypt == 'MD5':
            key = get_md5(enctry_str)
        return key

    # 获取h5st所需动态算法,rd
    def get_h5st_token(self, ai, headers, payload):
        url = 'https://cactus.jd.com/request_algo?g_ty=ajax'
        resp = self.sess.post(url=url, headers=headers, json=payload)
        result = json.loads(resp.text)
        if result['status'] == 200:
            self.h5st_algo[ai]['tk'] = result['data']['result']['tk']
            algo = result['data']['result']['algo']
            self.h5st_algo[ai]['rd'] = re.search(r'rd=\'(.*?)\'', algo).group(1)
            self.h5st_algo[ai]['enc'] = re.search(r'return algo\.(.*?)\(', algo).group(1)

    # 3.1版本算法
    def get_h5st_v43(self, signStr, ai, date, ts, key):
        extra = {
            'sua': 'Linux; Android 11; SM-G9980 Build/RP1A.200720.012; wv',
            'pp': {
                'p1': self.pin,
                'p2': self.pin
            },
            'extend': {
                'wd': 0,
                'l': 0,
                'ls': 0,
                'wk': 0,
                'bu1': '0.1.10',
                'bu2': -1,
                'bu3': 37,
                'bu4': 0
            },
            'random': generate_random_string(10),
            'v': 'h5_file_v4.3.3',
            'fp': self.h5st_algo[ai]['fp']
        }
        tk = self.h5st_algo[ai]['tk']
        fp = self.h5st_algo[ai]['fp']
        sign = get_hmacsha256(key=key, data=signStr)
        return date + ';' + fp + ';' + ai + ';' + tk + ';' + sign + ';4.3;' + ts + ';' + self.aes_encrypt(
            body=json.dumps(extra), key='&d74&yWoV.EYbWbZ')

    # 4.1版本算法
    def get_h5st_v41(self, signStr, ai, date, ts):
        extra = {
            'sua': 'Linux; Android 11; SM-G9980 Build/RP1A.200720.012; wv',
            'pp': {
                'p1': self.pin
            },
            'extend': {
                'pm': 0,
                'wd': 0,
                'l': 0,
                'ls': 0,
                'wk': 0
            },
            'random': generate_random_string(10),
            'referer': "https://m.jd.com/",
            "v": "v1.6.1",
            'fp': self.h5st_algo[ai]['fp']
        }
        tk = self.h5st_algo[ai]['tk']
        fp = self.h5st_algo[ai]['fp']
        sign = get_md5(signStr)
        return date + ';' + fp + ';' + ai + ';' + tk + ';' + sign + ';4.1;' + ts + ';' + self.aes_encrypt(
            body=json.dumps(extra), key='HL4|FW#Chc3#q?0)')

    def booking_info(self, skuid, area):
        date = get_date()[0]
        ts = get_date()[1]
        headers = {
            'User-Agent': self.seckillUserAgent,
            'Content-Type': 'application/x-www-form-urlencoded',
            'Referer': 'https://trade.m.jd.com/',
            'Origin': 'https://trade.m.jd.com',
            'X-Referer-Page': 'https://trade.m.jd.com/pay',
            'x-rp-client': 'h5_1.0.0',
            'X-Requested-With': 'com.jingdong.app.mall'
        }
        body = {
            'deviceUUID': 'unknow',
            'appId': 'wxae3e8056daea8727',
            'appVersion': '2.2.7',
            'tenantCode': 'jgm',
            'bizModelCode': '3',
            'bizModeClientType': 'M',
            'token': '3852b12f8c4d869b7ed3e2b3c68c9436',
            'externalLoginType': 1,
            'resetGsd': 'true',
            'useBestCoupon': '1',
            'locationId': '',
            'packageStyle': 'true',
            'balanceCommonOrderForm': {'action': 4, 'overseaMerge': 'false', 'preSalePaymentTypeInOptional': 2,
                                       'international': 'false',
                                       'netBuySourceType': 0, 'appVersion': '2.2.7', 'supportTransport': 'false',
                                       'tradeShort': 'false'},

            'cartParam': {'skuItem': {'skuId': skuid, 'num': '1', 'orderCashBack': 'false'}},
            'balanceDeviceInfo': {'resolution': '390*844'},
        }
        url = 'https://api.m.jd.com/client.action'
        enctry_str = self.h5st_algo['bd265']['tk'] + self.h5st_algo['bd265']['fp'] + date + '22' + 'bd265' + \
                     self.h5st_algo['bd265']['rd']
        t = str(round(time.time() * 1000))
        key = self.get_h5st_signStr_key(ai='bd265', enctry_str=enctry_str)
        body = dict_json(body)
        signStr = 'appid:m_core' + '&body:' + get_sha256(
            data=body) + '&client:Linux aarch64&clientVersion:2.2.7&functionId:balance_getCurrentOrder_m&t:' + t
        params = {
            'client': 'Linux aarch64',
            'clientVersion': '2.2.7',
            'osVersion': 'other',
            'screen': '390*844',
            'networkType': 'false',
            'd_brand': '',
            'd_model': '',
            'lang': 'zh-CN',
            'sdkVersion': '2.2.7',
            'appid': 'm_core',
            'openudid': '',
            'functionId': 'balance_getCurrentOrder_m',
            'uuid': '',  # str(uuid.uuid4()).replace('-', ''),
            'loginType': '2',
            't': t,
            'body': body,
            'h5st': self.get_h5st_v43(signStr=signStr, ai='bd265', date=date, ts=ts, key=key),
            'x-api-eid-token': self.x_api_eid_token
        }

        resp = self.sess.get(url=url, headers=headers, params=params)
        self.orderInfo[skuid] = json.loads(resp.text)['body']

    def booking_good(self, skuid):
        """
        预售模式-全款
        """
        t = str(round(time.time() * 1000))
        date = get_date()[0]
        ts = get_date()[1]
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'Host': 'api.m.jd.com',
            'User-Agent': self.seckillUserAgent,
            'Origin': 'https://trade.m.jd.com/',
            'Referer': 'https://trade.m.jd.com/',
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-Referer-Page': 'https://trade.m.jd.com/pay',
            'X-Rp-Client': 'h5_1.0.0',
            'X-Requested-With': 'com.jingdong.app.mall'
        }
        body = {
            'deviceUUID': 'unknown',
            'appId': 'wxae3e8056daea8727',
            'tenantCode': 'jgm',
            'bizModelCode': '3',
            'bizModeClientType': 'M',
            'token': '3852b12f8c4d869b7ed3e2b3c68c9436',
            'externalLoginType': 1,
            'appVersion': '2.2.7',
            'checkPayPassport': 'false',
            'checkpwdV2': 'false',
            'isEncryptionMobile': 'true',
            'outStockVendorIdList': [0],
            'mainSkuIdList': [skuid],
            'balanceDataServerSkuVOList': [{'id': skuid, 'buyNum': 1, 'firstCategoryId':
                self.orderInfo[skuid]['balanceVendorBundleList'][0]['bundleList'][0]['productionList'][0][
                    'balanceSkuList'][0]['firstCategoryId'], 'secondCategoryId':
                                                self.orderInfo[skuid]['balanceVendorBundleList'][0]['bundleList'][
                                                    0][
                                                    'productionList'][0]['balanceSkuList'][0]['secondCategoryId'],
                                            'thirdCategoryId':
                                                self.orderInfo[skuid]['balanceVendorBundleList'][0]['bundleList'][
                                                    0][
                                                    'productionList'][0]['balanceSkuList'][0]['thirdCategoryId'],
                                            'promoId':
                                                self.orderInfo[skuid]['balanceVendorBundleList'][0]['bundleList'][
                                                    0]['productionList'][0][
                                                    'balanceSkuList'][0]['promotion']['promoId'], 'venderId': 0,
                                            'type': 1}
                                           ],
            'payStepType': '5',
            'cashierDeskBackUrl': '',
            'payType': '4',
            'licenseList': '',
            'balanceCommonOrderForm': {'action': 4, 'overseaMerge': 'false', 'preSalePaymentTypeInOptional': 2,
                                       'international': 'false',
                                       'netBuySourceType': 0, 'appVersion': '2.2.7', 'supportTransport': 'false',
                                       'tradeShort': 'false'},
            'balanceExt': {'bubbleTips': {'enable': 'true', 'num': 1, 'time': 3, 'useNum': ''},
                           'cashierDeskEnable': 'true', 'checkIdInfo': 'false', 'couponRedText': '', 'hasCwbg': 'false',
                           'hasFreightInsurance': 'false', 'isInternational': 'false', 'isSupportTranport': 'false',
                           'jdCombineType': 0, 'knowledgeServiceStatus': 0, 'overseaMerge': 'false',
                           'selectedCouponNum': 0, 'sellLargeDay': '7 ', 'supportPaymentSkuList': [skuid],
                           'useBestCoupon': 'true'},
            'dsList': [
                {'paramName': 'report_time', 'paramVal': ''}, {'paramName': 'deal_id', 'paramVal': ''},
                {'paramName': 'buyer_uin'}, {'paramName': 'pin', 'paramVal': ''},
                {'paramName': 'cookie_pprd_p', 'paramVal': ''}, {'paramName': 'cookie_pprd_s', 'paramVal': ''},
                {'paramName': 'cookie_pprd_t', 'paramVal': ''}, {'paramName': 'ip', 'paramVal': ''},
                {'paramName': 'visitkey', 'paramVal': ''}, {'paramName': 'gen_entrance', 'paramVal': ''},
                {'paramName': 'deal_src', 'paramVal': '7'}, {'paramName': 'item_type', 'paramVal': '1'},
                {'paramName': 'fav_unixtime', 'paramVal': ''}, {'paramName': 'pay_type', 'paramVal': '0'},
                {'paramName': 'ab_test', 'paramVal': ''}, {'paramName': 'serilize_type', 'paramVal': '0'},
                {'paramName': 'property1', 'paramVal': '0'}, {'paramName': 'property2', 'paramVal': '0'},
                {'paramName': 'property3', 'paramVal': '0'}, {'paramName': 'property4', 'paramVal': '0'},
                {'paramName': 'seller_uin', 'paramVal': '0'}, {'paramName': 'pp_item_id', 'paramVal': ''},
                {'paramName': 'openid', 'paramVal': ''}, {'paramName': 'orderprice', 'paramVal': ''},
                {'paramName': 'actiontype', 'paramVal': ''}, {'paramName': 'extinfo', 'paramVal': ''},
                {'paramName': 'ext1', 'paramVal': ''}, {'ext2': 'paramName', 'paramVal': ''},
                {'paramName': 'ext3', 'paramVal': ''}, {'ext4': 'paramName', 'paramVal': ''},
                {'paramName': 'ext5', 'paramVal': ''}, {'paramName': 'ext6', 'paramVal': ''},
                {'paramName': 'ext7', 'paramVal': ''}, {'paramName': 'ext8', 'paramVal': '0'},
                {'paramName': 'ext9', 'paramVal': '0|0|0|0|0||0|0'}, {'paramName': 'ext10', 'paramVal': '|||'},
                {'paramName': 'ext11', 'paramVal': 'http://wq.jd.com/wxapp/pages/pay/index/index'},
                {'paramName': 'ext12', 'paramVal': '1'},
                {'paramName': 'ext13', 'paramVal': ''}, {'paramName': 'ext14', 'paramVal': ''},
                {'paramName': 'ext15', 'paramVal': ''}, {'paramName': 'ext16', 'paramVal': ''},
                {'paramName': 'ext17', 'paramVal': ''}, {'paramName': 'ext18', 'paramVal': ''},
                {'paramName': 'ext19', 'paramVal': ''}, {'paramName': 'ext20', 'paramVal': ''},
                {'paramName': 'fpa', 'paramVal': ''}, {'paramName': 'fpb', 'paramVal': ''},
                {'paramName': 'ext21', 'paramVal': ''}, {'paramName': 'ext22', 'paramVal': ''},
                {'paramName': 'ext23', 'paramVal': 'NULL'}, {'paramName': 'ext24', 'paramVal': 'NULL'},
                {'paramName': 'ext25', 'paramVal': 'NULL'}, {'paramName': 'ext26', 'paramVal': 'NULL'},
                {'paramName': 'ext27', 'paramVal': 'NULL'}, {'paramName': 'ext28', 'paramVal': 'NULL'},
                {'paramName': 'ext29', 'paramVal': 'NULL'}, {'paramName': 'ext30', 'paramVal': 'NULL'},
                {'paramName': 'ext31', 'paramVal': 'NULL'}, {'paramName': 'ext32', 'paramVal': 'NULL'},
                {'paramName': 'ext33', 'paramVal': 'NULL'}, {'paramName': 'ext34', 'paramVal': 'NULL'},
                {'paramName': 'ext35', 'paramVal': 'NULL'}, {'paramName': 'ext36', 'paramVal': 'NULL'},
                {'paramName': 'ext37', 'paramVal': 'NULL'}, {'paramName': 'ext38', 'paramVal': 'NULL'},
                {'paramName': 'dt', 'paramVal': ''}

            ],
            'packageStyle': 'true',
            'sceneval': '2',
            'balanceDeviceInfo': {'resolution': '390*844'},
            'balanceId': self.orderInfo[skuid]['balanceId']
        }
        enctry_str = self.h5st_algo['cc85b']['tk'] + self.h5st_algo['cc85b']['fp'] + date + '22' + 'cc85b' + \
                     self.h5st_algo['cc85b']['rd']
        key = self.get_h5st_signStr_key(ai='cc85b', enctry_str=enctry_str)
        body = dict_json(body)
        signStr = 'appid:m_core' + '&body:' + get_sha256(
            data=body) + '&client:Linux aarch64&clientVersion:2.2.7&functionId:balance_submitOrder_m&t:' + t
        payload = {
            'appid': 'm_core',
            't': t,
            'uuid': self.uuid,
            'loginType': 2,
            'client': 'Linux aarch64',
            'clientVersion': '2.2.7',
            'osVersion': 'iOS',
            'screen': '844*390',
            'networkType': 'false',
            'd_brand': 'UnknownTablet',
            'd_model': 'UnknownTablet',
            'lang': 'zh-CN',
            'sdkVersion': '',
            'body': body,
            'functionId': 'balance_submitOrder_m',
            'h5st': self.get_h5st_v43(signStr=signStr, ai='cc85b', date=date, ts=ts, key=key),
            'x-api-eid-token': self.x_api_eid_token
        }
        try:
            self.ui.console.append("{0}   开始提交订单".format(get_current_time()))
            resp = self.sess.post(url=url, headers=headers, data=payload)
            resp_json = json.loads(resp.text)['body']
            if resp_json.get('errorCode'):
                if resp_json.get('noStockSkuList'):
                    self.ui.console.append(
                        "{0}   {1}无货".format(get_current_time(), resp_json['noStockSkuList'][0]['name']))
                else:
                    self.ui.console.append("{0}   {1}".format(get_current_time(), resp_json['errorReason']))
                return False
            else:
                self.ui.console.append("{0}   恭喜抢购成功".format(get_current_time()))
                if self.send_message:
                    key = global_config.get('messenger', 'sckey')
                    params = {
                        'text': '{0}抢购成功下单提醒'.format(self.user),
                        'desp': '恭喜:' + self.user + '成功下单:' + skuid + ',快去付款吧'
                    }
                    requests.get(url='https://sctapi.ftqq.com/{0}.send'.format(key), params=params)
                    self.app.getPayChannel(orderId=resp_json['order']['orderId'],
                                           orderType=resp_json['order']['orderType'],
                                           totalPrice=resp_json['order']['orderPrice'])
                    return True
                return True
        except:
            self.ui.console.append("{0}   提交出错或提取代付链接出现异常".format(get_current_time()))
            return False

    def get_currentOrder_token(self, skuid):
        self.h5st_algo['bd265']['fp'] = get_fp43()
        expandParams = {
            'wc': 0,
            'wd': 0,
            'l': 'zh-CN',
            'ls': 'zh-CN,zh',
            'ml': 0,
            'pl': 0,
            'av': self.seckillUserAgent[self.seckillUserAgent.find("appBuild/") + len("appBuild/"):],
            'ua': self.seckillUserAgent,
            'sua': 'Linux; Android 11; SM-G9980 Build/RP1A.200720.012; wv',
            'pp': {'p1': self.pin, 'p2': self.pin},
            'extend': {
                'wd': 0,
                'l': 0,
                'ls': 0,
                'wk': 0,
                'bu1': '0.1.10',
                'bu2': 0,
                'bu3': 37,
                'bu4': 0
            },
            'pp1': '',
            'w': 390,
            'h': 844,
            'ow': 390,
            'oh': 844,
            'url': 'https://trade.m.jd.com/pay?commlist={0},,1,{0},1,0,0'.format(
                skuid, skuid),
            'og': 'https://trade.m.jd.com',
            'pr': 3.75,
            're': '',
            'random': generate_random_string(10),
            'referer': '',
            'v': 'h5_file_v4.3.3',
            'ai': 'bd265',
            'fp': self.h5st_algo['bd265']['fp']
        }
        algoHeaders = {
            'Host': 'cactus.jd.com',
            'Origin': 'https://trade.m.jd.com',
            'Referer': 'https://trade.m.jd.com/',
            'User-Agent': self.seckillUserAgent,
            'Content-Type': 'application/json',
            'x-rp-client': 'h5_1.0.0',
            'X-Requested-With': 'com.jingdong.app.mall',
        }
        algoPayload = {
            'version': '4.3',
            'fp': self.h5st_algo['bd265']['fp'],
            'fv': 'h5_file_v4.3.3',
            'appId': 'bd265',
            'timestamp': str(round(time.time() * 1000)),
            'platform': 'web',
            'expandParams': self.aes_encrypt(body=json.dumps(expandParams), key='wm0!@w-s#ll1flo('),
        }
        self.get_h5st_token(ai='bd265', headers=algoHeaders, payload=algoPayload)

    def submit_balance_getCurrentOrder_m(self, skuid):
        date = get_date()[0]
        ts = get_date()[1]
        url = 'https://api.m.jd.com/client.action'
        header = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Origin': 'https://trade.m.jd.com',
            'Referer': 'https://trade.m.jd.com/',
            'X-Referer-Page': 'https://trade.m.jd.com/pay',
            'x-rp-client': 'h5_1.0.0',
            'X-Requested-With': 'com.jingdong.app.mall',
            'User-Agent': self.seckillUserAgent
        }
        body = {
            'deviceUUID': 'unknow',
            'appId': 'wxae3e8056daea8727',
            'appVersion': '2.2.7',
            'tenantCode': 'jgm',
            'bizModelCode': '3',
            'bizModeClientType': 'M',
            'token': '3852b12f8c4d869b7ed3e2b3c68c9436',
            'externalLoginType': 1,
            'resetGsd': 'true',
            'useBestCoupon': '1',
            'locationId': '',
            'packageStyle': 'true',
            'balanceCommonOrderForm': {
                'supportTransport': 'false',
                'action': 1,
                'overseaMerge': 'false',
                'international': 'false',
                'netBuySourceType': 0,
                'appVersion': '2.2.7',
                'tradeShort': 'false'
            },
            'balanceDeviceInfo': {'resolution': '390*844'},
            'cartParam': {
                'skuItem': {
                    'skuId': skuid,
                    'num': '1',
                    'orderCashBack': 'false',
                    'extFlag': {}
                }
            }
        }
        enctry_str = self.h5st_algo['bd265']['tk'] + self.h5st_algo['bd265']['fp'] + date + '22' + 'bd265' + \
                     self.h5st_algo['bd265']['rd']
        t = str(round(time.time() * 1000))
        key = self.get_h5st_signStr_key(ai='bd265', enctry_str=enctry_str)
        body = dict_json(body)
        signStr = 'appid:m_core&body:' + get_sha256(
            body) + '&client:Linux aarch64&clientVersion:2.2.7&functionId:balance_getCurrentOrder_m&t:' + t

        params = {
            'client': 'Linux aarch64',
            'clientVersion': '2.2.7',
            'osVersion': 'other',
            'screen': '390*844',
            'networkType': 'false',
            'd_brand': '',
            'd_model': '',
            'lang': 'zh-CN',
            'sdkVersion': '2.2.7',
            'appid': 'm_core',
            'openudid': '',
            'functionId': 'balance_getCurrentOrder_m',
            'uuid': '',  # str(uuid.uuid4()).replace('-', ''),
            'loginType': '2',
            't': t,
            'body': body,
            'h5st': self.get_h5st_v43(signStr=signStr, ai='bd265', date=date, ts=ts, key=key),
            'x-api-eid-token': self.x_api_eid_token
        }

        resp = self.sess.post(url=url, headers=header, data=params)
        self.orderInfo[skuid] = json.loads(resp.text)['body']

    def get_submit_token(self, skuid):
        self.h5st_algo['cc85b']['fp'] = get_fp43()
        expandParams = {
            'wc': 0,
            'wd': 0,
            'l': 'zh-CN',
            'ls': 'zh-CN,zh',
            'ml': 0,
            'pl': 0,
            'av': self.seckillUserAgent[self.seckillUserAgent.find("appBuild/") + len("appBuild/"):],
            'ua': self.seckillUserAgent,
            'sua': 'Linux; Android 11; SM-G9980 Build/RP1A.200720.012; wv',
            'pp': {'p1': self.pin, 'p2': self.pin},
            'extend': {
                'wd': 0,
                'l': 0,
                'ls': 0,
                'wk': 0,
                'bu1': '0.1.10',
                'bu2': 0,
                'bu3': 37,
                'bu4': 0
            },
            'pp1': '',
            'w': 390,
            'h': 844,
            'ow': 390,
            'oh': 844,
            'url': 'https://trade.m.jd.com/pay?commlist={0},,1,{0},1,0,0'.format(
                skuid, skuid),
            'og': 'https://trade.m.jd.com',
            'pr': 3.75,
            're': '',
            'random': generate_random_string(10),
            'referer': '',
            'v': 'h5_file_v4.3.3',
            'ai': 'cc85b',
            'fp': self.h5st_algo['cc85b']['fp']
        }
        algoHeaders = {
            'Host': 'cactus.jd.com',
            'Origin': 'https://trade.m.jd.com',
            'Referer': 'https://trade.m.jd.com/',
            'User-Agent': self.ua,
            'Content-Type': 'application/json',
            'x-rp-client': 'h5_1.0.0',
            'X-Requested-With': 'com.jingdong.app.mall',
        }
        algoPayload = {
            'version': '4.3',
            'fp': self.h5st_algo['cc85b']['fp'],
            'fv': 'h5_file_v4.3.3',
            'appId': 'cc85b',
            'timestamp': str(round(time.time() * 1000)),
            'platform': 'web',
            'expandParams': self.aes_encrypt(body=json.dumps(expandParams), key='wm0!@w-s#ll1flo('),
        }
        self.get_h5st_token(ai='cc85b', headers=algoHeaders, payload=algoPayload)

    def submit_order(self, skuid):
        t = str(round(time.time() * 1000))
        date = get_date()[0]
        ts = get_date()[1]
        url = 'https://api.m.jd.com/client.action'
        headers = {
            'Host': 'api.m.jd.com',
            'User-Agent': self.seckillUserAgent,
            'Origin': 'https://trade.m.jd.com',
            'Referer': 'https://trade.m.jd.com/',
            'X-Referer-Page': 'https://trade.m.jd.com/pay',
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-Rp-Client': 'h5_1.0.0',
            'X-Requested-With': 'com.jingdong.app.mall'
        }
        body = {
            'deviceUUID': 'unknown',
            'appId': 'wxae3e8056daea8727',
            'tenantCode': 'jgm',
            'bizModelCode': '3',
            'bizModeClientType': 'M',
            'token': '3852b12f8c4d869b7ed3e2b3c68c9436',
            'externalLoginType': 1,
            'appVersion': '2.2.7',
            'checkPayPassport': 'false',
            'checkpwdV2': 'false',
            'isEncryptionMobile': 'true',
            'outStockVendorIdList': [0],
            'mainSkuIdList': [skuid],
            'balanceDataServerSkuVOList': [{'id': skuid, 'buyNum': 1, 'firstCategoryId':
                self.orderInfo[skuid]['balanceVendorBundleList'][0]['bundleList'][0]['productionList'][0][
                    'balanceSkuList'][0]['firstCategoryId'], 'secondCategoryId':
                                                self.orderInfo[skuid]['balanceVendorBundleList'][0]['bundleList'][
                                                    0][
                                                    'productionList'][0]['balanceSkuList'][0]['secondCategoryId'],
                                            'thirdCategoryId':
                                                self.orderInfo[skuid]['balanceVendorBundleList'][0]['bundleList'][
                                                    0][
                                                    'productionList'][0]['balanceSkuList'][0]['thirdCategoryId'],
                                            'promoId':
                                                self.orderInfo[skuid]['balanceVendorBundleList'][0]['bundleList'][
                                                    0]['productionList'][0][
                                                    'balanceSkuList'][0]['promotion']['promoId'], 'venderId': 0,
                                            'type': 1}
                                           ],
            'cashierDeskBackUrl': 'https://wqs.jd.com/order/paysuc.shtml?dealId=%24%7BorderId%7D&sceneval=2&fromPay=1&ptag=7039.27.14&gift_skuid={0}&gift_venderid=0&gift_cid=655&normal=1'.format(
                skuid),
            'payType': '4',
            'subPayType': '',
            'licenseList': [],
            'balanceCommonOrderForm': {'action': 1, 'overseaMerge': 'false', 'international': 'false',
                                       'netBuySourceType': 0, 'appVersion': '2.2.7', 'supportTransport': 'false',
                                       'tradeShort': 'false'},
            'balanceExt': {'bubbleTips': {'enable': 'true', 'num': 1, 'time': 3, 'useNum': 1},
                           'cashierDeskEnable': 'true', 'cashierPayFlag': '0', 'checkIdInfo': 'false',
                           'couponRedText': '',
                           'hasBackupStorage': 'false', 'hasCwbg': 'false',
                           'hasFreightInsurance': 'false', 'isHideTitle': 'true', 'isInternational': 'false',
                           'isSupportTranport': 'false',
                           'jdCombineType': 0, 'knowledgeServiceStatus': 0, 'overseaMerge': 'false',
                           'selectedCouponNum': 0, 'sellLargeDay': '7 ', 'supportPaymentSkuList': [skuid],
                           'useBestCoupon': 'true'},
            'dsList': [
                {'paramName': 'report_time', 'paramVal': ''}, {'paramName': 'deal_id', 'paramVal': ''},
                {'paramName': 'buyer_uin'}, {'paramName': 'pin', 'paramVal': ''},
                {'paramName': 'cookie_pprd_p', 'paramVal': ''}, {'paramName': 'cookie_pprd_s', 'paramVal': ''},
                {'paramName': 'cookie_pprd_t', 'paramVal': ''}, {'paramName': 'ip', 'paramVal': ''},
                {'paramName': 'visitkey', 'paramVal': ''}, {'paramName': 'gen_entrance', 'paramVal': ''},
                {'paramName': 'deal_src', 'paramVal': '7'}, {'paramName': 'item_type', 'paramVal': '1'},
                {'paramName': 'fav_unixtime', 'paramVal': ''}, {'paramName': 'pay_type', 'paramVal': '0'},
                {'paramName': 'ab_test', 'paramVal': ''}, {'paramName': 'serilize_type', 'paramVal': '0'},
                {'paramName': 'property1', 'paramVal': '0'}, {'paramName': 'property2', 'paramVal': '0'},
                {'paramName': 'property3', 'paramVal': '0'}, {'paramName': 'property4', 'paramVal': '0'},
                {'paramName': 'seller_uin', 'paramVal': '0'}, {'paramName': 'pp_item_id', 'paramVal': ''},
                {'paramName': 'openid', 'paramVal': ''}, {'paramName': 'orderprice', 'paramVal': ''},
                {'paramName': 'actiontype', 'paramVal': ''}, {'paramName': 'extinfo', 'paramVal': ''},
                {'paramName': 'ext1', 'paramVal': ''}, {'ext2': 'paramName', 'paramVal': ''},
                {'paramName': 'ext3', 'paramVal': ''}, {'ext4': 'paramName', 'paramVal': ''},
                {'paramName': 'ext5', 'paramVal': ''}, {'paramName': 'ext6', 'paramVal': ''},
                {'paramName': 'ext7', 'paramVal': ''}, {'paramName': 'ext8', 'paramVal': '0'},
                {'paramName': 'ext9', 'paramVal': '0|0|0|0|0||0|0'}, {'paramName': 'ext10', 'paramVal': '|||'},
                {'paramName': 'ext11', 'paramVal': 'http://wq.jd.com/wxapp/pages/pay/index/index'},
                {'paramName': 'ext12', 'paramVal': '1'},
                {'paramName': 'ext13', 'paramVal': ''}, {'paramName': 'ext14', 'paramVal': ''},
                {'paramName': 'ext15', 'paramVal': ''}, {'paramName': 'ext16', 'paramVal': ''},
                {'paramName': 'ext17', 'paramVal': ''}, {'paramName': 'ext18', 'paramVal': ''},
                {'paramName': 'ext19', 'paramVal': ''}, {'paramName': 'ext20', 'paramVal': ''},
                {'paramName': 'fpa', 'paramVal': ''}, {'paramName': 'fpb', 'paramVal': ''},
                {'paramName': 'ext21', 'paramVal': ''}, {'paramName': 'ext22', 'paramVal': ''},
                {'paramName': 'ext23', 'paramVal': 'NULL'}, {'paramName': 'ext24', 'paramVal': 'NULL'},
                {'paramName': 'ext25', 'paramVal': 'NULL'}, {'paramName': 'ext26', 'paramVal': 'NULL'},
                {'paramName': 'ext27', 'paramVal': 'NULL'}, {'paramName': 'ext28', 'paramVal': 'NULL'},
                {'paramName': 'ext29', 'paramVal': 'NULL'}, {'paramName': 'ext30', 'paramVal': 'NULL'},
                {'paramName': 'ext31', 'paramVal': 'NULL'}, {'paramName': 'ext32', 'paramVal': 'NULL'},
                {'paramName': 'ext33', 'paramVal': 'NULL'}, {'paramName': 'ext34', 'paramVal': 'NULL'},
                {'paramName': 'ext35', 'paramVal': 'NULL'}, {'paramName': 'ext36', 'paramVal': 'NULL'},
                {'paramName': 'ext37', 'paramVal': 'NULL'}, {'paramName': 'ext38', 'paramVal': 'NULL'},
                {'paramName': 'dt', 'paramVal': ''}

            ],
            'packageStyle': 'true',
            'balanceDeviceInfo': {'resolution': '390*844'},
            'balanceId': self.orderInfo[skuid]['balanceId']
        }
        enctry_str = self.h5st_algo['cc85b']['tk'] + self.h5st_algo['cc85b']['fp'] + date + '22' + 'cc85b' + \
                     self.h5st_algo['cc85b']['rd']
        key = self.get_h5st_signStr_key(ai='cc85b', enctry_str=enctry_str)
        body = dict_json(body)
        signStr = 'appid:m_core' + '&body:' + get_sha256(
            data=body) + '&client:Linux aarch64&clientVersion:2.2.7&functionId:balance_submitOrder_m&t:' + t
        payload = {
            'appid': 'm_core',
            't': t,
            'uuid': self.uuid,
            'loginType': 2,
            'client': 'Linux aarch64',
            'clientVersion': '2.2.7',
            'osVersion': 'iOS',
            'screen': '844*390',
            'networkType': 'false',
            'd_brand': 'UnknownTablet',
            'd_model': 'UnknownTablet',
            'lang': 'zh-CN',
            'sdkVersion': '',
            'body': body,
            'functionId': 'balance_submitOrder_m',
            'h5st': self.get_h5st_v43(signStr=signStr, ai='cc85b', date=date, ts=ts, key=key),
            'x-api-eid-token': self.x_api_eid_token
        }
        try:
            self.ui.console.append("{0}   开始提交订单".format(get_current_time()))
            resp = self.sess.post(url=url, headers=headers, data=payload)
            resp_json = json.loads(resp.text)['body']
            if resp_json.get('errorCode'):
                if resp_json.get('noStockSkuList'):
                    self.ui.console.append(
                        "{0}   {1}无货".format(get_current_time(), resp_json['noStockSkuList'][0]['name']))
                else:
                    self.ui.console.append("{0}   {1}".format(get_current_time(), resp_json['errorReason']))
                return False
            else:
                self.ui.console.append("{0}   恭喜抢购成功".format(get_current_time()))
                if self.send_message:
                    key = global_config.get('messenger', 'sckey')
                    params = {
                        'text': '{0}抢购成功下单提醒'.format(self.user),
                        'desp': '恭喜:' + self.user + '成功下单:' + skuid + ',快去付款吧'
                    }
                    requests.get(url='https://sctapi.ftqq.com/{0}.send'.format(key), params=params)
                    print('推送成功')
                    self.app.getPayChannel(orderId=resp_json['order']['orderId'],
                                           orderType=resp_json['order']['orderType'],
                                           totalPrice=resp_json['order']['orderPrice'])
                    return True
                return True
        except:
            self.ui.console.append("{0}   提交出错或提取代付链接出现异常".format(get_current_time()))
            return False

    def seckill_order_info(self, sku):
        date = get_date()[0]
        ts = get_date()[1]
        url = 'https://api.m.jd.com/api'
        headers = {
            'Origin': 'https://wqs.jd.com',
            'User-Agent': self.seckillUserAgent,
            'Referer': 'https://wqs.jd.com/order/jx_confirm_miao.shtml?skuId={0}&num=1&sid=&un_area={1}'.format(sku,
                                                                                                                self.area),
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-Referer-Page': 'https://wqs.jd.com/order/jx_confirm_miao.shtml',
            'X-Rp-Client': 'h5_1.0.0',
            'X-Requested-With': 'com.jd.jdlite'
        }
        t = round(time.time() * 1000)
        body = {
            'cmdylist': [{'itemId': sku, 'num': '1'}],
            'resetcoupon': '1',
            'paychannel': 2,
            'toppaychannel': 0,
            'fixednum': '',
            'skulist': '',
            'traceid': self.traceId,
            'h5page': 1,
            'sceneval': 2,
            'buid': 325,
            'appCode': 'ms2362fc9e',
            'time': t,
        }
        sign = getSignStr(data=body)
        body['signStr'] = sign
        enctry_str = self.h5st_algo['12bda']['tk'] + self.h5st_algo['12bda']['fp'] + date + '22' + '12bda' + \
                     self.h5st_algo['12bda']['rd']
        key = self.get_h5st_signStr_key(ai='12bda', enctry_str=enctry_str)
        body = dict_json(body)
        signStr = 'appid:jx_h5' + '&body:' + get_sha256(
            data=body) + '&client:jxh5&clientVersion:1.2.5&functionId:jxt_miao_orderinfo&t:' + str(t)
        payload = {
            'channel': 'jxh5',
            'cv': '1.2.5',
            'clientVersion': '1.2.5',
            'client': 'jxh5',
            'uuid': self.uuid,
            'body': body,
            't': t,
            'functionId': 'jxt_miao_orderinfo',
            'appid': 'jx_h5',
            'loginType': 2,
            'cthr': 1,
            'h5st': self.get_h5st_v43(signStr=signStr, ai='12bda', date=date, ts=ts, key=key),
            'x-api-eid-token': self.x_api_eid_token
        }
        try:
            self.sess.post(url=url, headers=headers, data=payload)
        except Exception as e:
            self.ui.console.append("{0}   请求抢购订单数据出错".format(get_current_time()))

    def seckill_getToken(self, skuid):
        self.h5st_algo['12bda']['fp'] = get_fp43()
        expandParams = {
            'wc': 0,
            'wd': 0,
            'l': 'zh-CN',
            'ls': 'zh-CN,zh',
            'ml': 0,
            'pl': 0,
            'av': self.seckillUserAgent[self.seckillUserAgent.find("appBuild/") + len("appBuild/"):],
            'ua': self.seckillUserAgent,
            'sua': 'Linux; Android 11; SM-G9980 Build/RP1A.200720.012; wv',
            'pp': {'p1': self.pin},
            'extend': {
                'wd': 0,
                'l': 0,
                'ls': 0,
                'wk': 0,
                'bu1': '0.1.10',
                'bu2': 0,
                'bu3': 37,
                'bu4': 0
            },
            'pp1': '',
            'w': 400,
            'h': 904,
            'ow': 400,
            'oh': 904,
            'url': 'https://wqs.jd.com/order/jx_confirm_miao.shtml?linkfrom=npmpkg&skuId={0}&num=1&venderType=-1&__navVer=1&appCode=ms2362fc9e'.format(
                skuid),
            'og': 'https://wqs.jd.com',
            'pr': 2.750000596046448,
            're': '',
            'random': generate_random_string(10),
            'referer': '',
            'v': 'h5_file_v4.3.3',
            'ai': '12bda',
            'fp': self.h5st_algo['12bda']['fp']
        }
        algoHeaders = {
            'Host': 'cactus.jd.com',
            'Origin': 'https://plus.m.jd.com',
            'Referer': 'https://plus.m.jd.com/user/home',
            'User-Agent': self.seckillUserAgent,
            'Content-Type': 'application/json',
            'x-rp-client': 'h5_1.0.0',
            'X-Requested-With': 'com.jd.jdlite',
        }
        algoPayload = {
            'version': '4.3',
            'fp': self.h5st_algo['12bda']['fp'],
            'appId': '12bda',
            'timestamp': str(round(time.time() * 1000)),
            'platform': 'web',
            'expandParams': self.aes_encrypt(body=json.dumps(expandParams), key='wm0!@w-s#ll1flo('),
            'fv': 'h5_file_v4.3.3'
        }
        self.get_h5st_token(ai='12bda', headers=algoHeaders, payload=algoPayload)

    def seckill_submit_order(self, skuid):
        self.ui.console.append("{0}   开始提交订单".format(get_current_time()))
        date = get_date()[0]
        ts = get_date()[1]
        url = 'https://api.m.jd.com/api'
        headers = {
            'Host': 'api.m.jd.com',
            'User-Agent': self.seckillUserAgent,
            'Referer': 'https://wqs.jd.com/order/jx_confirm_miao.shtml?skuId={0}&num=1&sid=&un_area={1}'.format(skuid,
                                                                                                                self.area),
            'Origin': 'https://wqs.jd.com',
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-Referer-Page': 'https://wqs.jd.com/order/jx_confirm_miao.shtml',
            'X-Rp-Client': 'h5_1.0.0',
            'X-Requested-With': 'com.jd.jdlite'
        }
        t = round(time.time() * 1000)
        enctry_str = self.h5st_algo['12bda']['tk'] + self.h5st_algo['12bda']['fp'] + date + '22' + '12bda' + \
                     self.h5st_algo['12bda']['rd']
        key = self.get_h5st_signStr_key(ai='12bda', enctry_str=enctry_str)
        body = {
            'addressid': self.aid,
            'paytype': 4,
            'paychannel': 2,
            'cmdylist': [{'itemId': skuid, 'num': 1}],
            'resetcoupon': '1',
            'toppaychannel': 0,
            'fixednum': '',
            'skulist': '',
            'traceid': self.traceId,
            'h5page': 1,
            'sceneval': 2,
            'buid': 325,
            'appCode': 'ms2362fc9e',
            'time': t
        }
        sign = getSignStr(data=body)
        body['signStr'] = sign
        body = dict_json(body)
        signStr = 'appid:jx_h5' + '&body:' + get_sha256(
            data=body) + '&client:jxh5&clientVersion:1.2.5&functionId:jxt_miao_confirm&t:' + str(t)
        payload = {
            'channel': 'jxh5',
            'cv': '1.2.5',
            'clientVersion': '1.2.5',
            'client': 'jxh5',
            'uuid': self.uuid,
            'body': body,
            't': t,
            'functionId': 'jxt_miao_confirm',
            'appid': 'jx_h5',
            'loginType': 2,
            'cthr': 1,
            'h5st': self.get_h5st_v43(signStr=signStr, ai='12bda', date=date, ts=ts, key=key),
            'x-api-eid-token': self.x_api_eid_token
        }
        try:
            resp = self.sess.post(url=url, headers=headers, data=payload)
            resp_json = json.loads(resp.text)
            if resp_json.get('code'):
                self.ui.console.append("{0}   {1}".format(get_current_time(), resp_json['tips']))
                return False
            else:
                if resp_json['errId'] == 0:
                    self.ui.console.append("{0}   恭喜抢购成功".format(get_current_time()))
                    if self.send_message:
                        key = global_config.get('messenger', 'sckey')
                        params = {
                            'text': '{0}抢购成功下单提醒'.format(self.user),
                            'desp': '恭喜:' + self.user + '成功下单:' + skuid + ',快去付款吧'
                        }
                        requests.get(url='https://sctapi.ftqq.com/{0}.send'.format(key), params=params)
                        self.app.getPayChannel(orderId=resp_json['dealId'],
                                               orderType=resp_json['orderType'],
                                               totalPrice=resp_json['factPrice'].replace('¥', ''))
                        return True
                    return True
                else:
                    self.ui.console.append("{0}   {1}".format(get_current_time(), resp_json['errMsg']))
                    return False

        except Exception:
            self.ui.console.append("{0}   提交订单出错".format(get_current_time()))
            return False

    def submit_order_bytime(self, buy_time, skuid):
        """
        加车模式定时下单
        :return:
        """
        self.ui.console.append("{0}   正在等待到达设定时间:{1}".format(get_current_time(), buy_time))
        self.get_currentOrder_token(skuid=skuid)
        self.submit_balance_getCurrentOrder_m(skuid=skuid)
        while True:
            if self.orderInfo[skuid].get('errorCode'):
                self.ui.console.append(
                    "{0}   {1}--1s后重新请求".format(get_current_time(), self.orderInfo[skuid]['errorReason']))
                QApplication.processEvents()
                QtTest.QTest.qWait(1000)
                self.ui.console.append("{0}   开始重新请求订单数据".format(get_current_time()))
                self.submit_balance_getCurrentOrder_m(skuid=skuid)
            else:
                break
        pre = Timer(buy_time=buy_time)
        pre.pre_start()
        self.get_submit_token(skuid)
        t = Timer(buy_time=buy_time)
        t.start()
        if self.submit_order(skuid=skuid):
            return True

    def submit_order_bytime_not_pre(self, buy_time, skuid):
        """
        加车模式定时下单
        :return:
        """
        self.ui.console.append("{0}   正在等待到达设定时间:{1}".format(get_current_time(), buy_time))
        self.get_currentOrder_token(skuid=skuid)
        t = Timer(buy_time=buy_time)
        t.start()
        self.submit_balance_getCurrentOrder_m(skuid=skuid)
        while True:
            if self.orderInfo[skuid].get('errorCode'):
                self.ui.console.append(
                    "{0}   {1}--1s后重新请求".format(get_current_time(), self.orderInfo[skuid]['errorReason']))
                QApplication.processEvents()
                QtTest.QTest.qWait(1000)
                self.ui.console.append("{0}   开始重新请求订单数据".format(get_current_time()))
                self.submit_balance_getCurrentOrder_m(skuid=skuid)
            else:
                break
        self.get_submit_token(skuid=skuid)
        if self.submit_order(skuid=skuid):
            return True

    def seckill_submit_order_bytime(self, buy_time, skuid):
        """
        抢购模式定时下单
        :return:
        """
        self.traceId = self.random_char(19)
        self.ui.console.append("{0}   正在等待到达设定时间:{1}".format(get_current_time(), buy_time))
        self.seckill_getToken(skuid=skuid)
        self.seckill_order_info(sku=skuid)
        t = Timer(buy_time=buy_time)
        t.start()
        if self.seckill_submit_order(skuid=skuid):
            return True

    def yushou_dingjin_buytime(self, buy_time, skuid, area):
        """
        定金模式定时下单
        :param buy_time:
        :param skuid:
        :param area:
        :return:
        """
        self.ui.console.append("{0}   正在等待到达设定时间:{1}".format(get_current_time(), buy_time))
        self.get_currentOrder_token(skuid=skuid)
        t = Timer(buy_time=buy_time)
        t.start()
        self.booking_info(skuid=skuid, area=area)
        while True:
            if self.orderInfo[skuid].get('errorCode'):
                self.ui.console.append(
                    "{0}   {1}--1s后重新请求".format(get_current_time(), self.orderInfo[skuid]['errorReason']))
                QApplication.processEvents()
                QtTest.QTest.qWait(1000)
                self.ui.console.append("{0}   开始重新请求订单数据".format(get_current_time()))
                self.booking_info(skuid=skuid, area=area)
            else:
                break
        self.get_submit_token(skuid=skuid)
        if self.booking_good(skuid=skuid):
            return True
